using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace S.M.SmartMedical.Infrastructure.BaseRepository
{
    /// <summary>
    /// 通用仓储实现类
    /// 基于Entity Framework Core实现基础的CRUD操作
    /// </summary>
    /// <typeparam name="T">实体类型</typeparam>
    public class Repository<T> : IRepository<T> where T : class
    {
        /// <summary>
        /// 数据库上下文
        /// </summary>
        private readonly DbContext _context;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="context">数据库上下文</param>
        public Repository(DbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取所有实体
        /// </summary>
        /// <returns>实体集合</returns>
        public IQueryable<T> GetAllAsync()
        {
            return _context.Set<T>().AsQueryable();
        }

        /// <summary>
        /// 获取可查询的实体集合
        /// </summary>
        /// <returns>可查询的实体集合</returns>
        public IQueryable<T> GetQueryable()
        {
            return _context.Set<T>().AsQueryable();
        }

        /// <summary>
        /// 根据ID获取单个实体
        /// </summary>
        /// <param name="id">实体ID</param>
        /// <returns>实体对象</returns>
        public async Task<T?> GetByIdAsync(object id)
        {
            return await _context.Set<T>().FindAsync(id);
        }

        /// <summary>
        /// 根据条件获取单个实体
        /// </summary>
        /// <param name="predicate">查询条件</param>
        /// <returns>实体对象</returns>
        public async Task<T?> GetAsync(Expression<Func<T, bool>> predicate)
        {
            return await _context.Set<T>().FirstOrDefaultAsync(predicate);
        }

        /// <summary>
        /// 添加实体
        /// </summary>
        /// <param name="entity">要添加的实体</param>
        /// <returns>受影响的行数</returns>
        public async Task<int> AddAsync(T entity)
        {
            await _context.AddAsync(entity);
            return 1; // 返回1表示添加了一个实体，实际保存由调用者控制
        }

        /// <summary>
        /// 批量添加实体
        /// </summary>
        /// <param name="entities">要添加的实体集合</param>
        /// <returns>受影响的行数</returns>
        public async Task<int> AddRangeAsync(IEnumerable<T> entities)
        {
            var entitiesList = entities.ToList();
            await _context.AddRangeAsync(entitiesList);
            return entitiesList.Count; // 返回添加的实体数量，实际保存由调用者控制
        }

        /// <summary>
        /// 更新实体
        /// </summary>
        /// <param name="entity">要更新的实体</param>
        /// <returns>受影响的行数</returns>
        public async Task<int> UpdateAsync(T entity)
        {
            _context.Update(entity);
            return 1; // 返回1表示更新了一个实体，实际保存由调用者控制
        }

    }
}